package mn.more.mock.io.xml;

import java.io.File;
import java.io.IOException;
import java.util.List;
import junit.framework.TestCase;
import mn.more.foundation.io.FileOperator;
import mn.more.mock.io.MockDataReader;
import mn.more.mock.io.MockModel;

/**
 * @author <a href="mailto:mike.liu@aptechmongolia.edu.mn">Mike Liu</a>
 * @version $Id: WriterTestDrive.java 5 2008-09-01 12:08:42Z mikeliucc $
 */
public class WriterTestDrive extends TestCase {

	private static String filename = "/mock_model_test_drive.xml";
	private static String fileLocation;
	private MockModel user1;
	private MockModel person1;

	protected void setUp() throws Exception {
		fileLocation = getClass().getResource("/").getFile() + filename;
		user1 = new MockModel("user1");
		user1.setValue("userId", "userId_1");
		user1.setValue("password", "password_1");
		person1 = new MockModel("person1");
		person1.setValue("name", "person1_name");
		person1.setValue("age", 25);
		person1.setValue("profile", user1);
		super.setUp();
	}

	protected void tearDown() throws Exception {
		FileOperator.delete(fileLocation);
		super.tearDown();
	}

	public void testWriteAndRead() throws Exception {
		// test the writing process
		XMLWriter writer = new XMLWriter();
		try {
			writer.setFilename(filename, true);
			writer.write(person1);
		} catch (IOException e) {
			fail("failed at write(): " + e.getMessage());
		}

		// make sure that the file is really there
		File f = new File(fileLocation);
		assertNotNull(f);
		assertTrue(f.isFile());
		assertTrue(f.canRead());

		// test the reading process
		MockDataReader reader = new XMLReader();
		try {
			reader.setFilename(filename, true);
			reader.read();
		} catch (IOException e) {
			fail("failed at read(): " + e.getMessage());
		}

		List<String> ids = reader.getIdList();
		assertNotNull(ids);
		assertEquals(ids.size(), 2);
		assertTrue(ids.contains("user1"));
		assertTrue(ids.contains("person1"));

		MockModel _user1 = reader.getModel("user1");
		assertNotNull(_user1);
		assertEquals(_user1.getString("userId"), "userId_1");
		assertEquals(_user1.getString("password"), "password_1");

		MockModel _person1 = reader.getModel("person1");
		assertNotNull(_person1);
		assertEquals(_person1.getString("name"), "person1_name");
		assertEquals(_person1.getInt("age"), 25);
		assertEquals(_person1.getRefModel("profile"), _user1);
	}
}
